<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import VChart from 'vue-echarts';
import { useRouter } from 'vue-router';

import { usePreferences } from '@vben/preferences';

import {
  CloudUploadOutlined,
  DashboardOutlined,
  DatabaseOutlined,
  EyeOutlined,
  PieChartOutlined,
  RocketOutlined,
  SettingOutlined,
} from '@ant-design/icons-vue';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';

import { client } from '#/api/core/client';

interface UploadDownloadData {
  data: Array<{
    date: string;
    download: number;
    upload: number;
  }>;
}
interface StatsData {
  uploadedFiles: number;
  uploadedStorage: string;
  activeShares: number;
  networkSpeed: string;
  totalStorage: string;
  usedStorage: string;
  storageUsed: number;
}
interface FileTypeData {
  type: string;
  percentage: number;
  color: string;
}
interface RecentFile {
  id: string;
  name: string;
  size: string;
  uploadTime: string;
  type: string;
}

// 注册ECharts组件
echarts.use([
  BarChart,
  PieChart,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  CanvasRenderer,
]);

const { isDark } = usePreferences();

const stats = ref<StatsData>({
  uploadedFiles: 0,
  uploadedStorage: '0 GB',
  activeShares: 0,
  networkSpeed: '未连接',
  totalStorage: '0 GB',
  usedStorage: '0 GB',
  storageUsed: 0,
});
const uploadDownload = ref<UploadDownloadData>({
  data: [],
});
const fileTypes = ref<FileTypeData[]>([]);
const recentFiles = ref<RecentFile[]>([]);
const uploadDownloadOption = computed(() => {
  const textColor = isDark.value ? '#e5e7eb' : '#111827';
  const axisLineColor = isDark.value ? '#4b5563' : '#9ca3af';
  const splitLineColor = isDark.value
    ? 'rgba(75, 85, 99, 0.5)'
    : 'rgba(156, 163, 175, 0.3)';
  const uploadColor = isDark.value ? '#a78bfa' : '#7c3aed';
  const downloadColor = isDark.value ? '#67e8f9' : '#0891b2';

  return {
    title: {
      text: '上传/下载趋势(近7日)',
      left: 'center',
      textStyle: {
        color: textColor,
        fontSize: 12,
        fontFamily: 'SimSun, STKaiti, KaiTi, serif',
      },
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: isDark.value
        ? 'rgba(31, 41, 55, 0.9)'
        : 'rgba(255, 255, 255, 0.9)',
      borderColor: isDark.value ? '#4b5563' : '#d1d5db',
      textStyle: {
        color: isDark.value ? '#f3f4f6' : '#111827',
        fontFamily: 'SimSun, STKaiti, KaiTi, serif',
      },
    },
    legend: {
      data: ['上传', '下载'],
      bottom: 0,
      textStyle: {
        color: textColor,
        fontFamily: 'SimSun, STKaiti, KaiTi, serif',
      },
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '20%',
      top: '20%',
      backgroundColor: 'transparent',
    },
    xAxis: {
      type: 'category',
      data: uploadDownload.value.data.map((item) => item.date),
      axisLabel: {
        color: textColor,
        fontSize: 10,
        fontFamily: 'SimSun, STKaiti, KaiTi, serif',
      },
      axisLine: {
        lineStyle: {
          color: axisLineColor,
          width: 1,
        },
      },
      axisTick: {
        lineStyle: {
          color: axisLineColor,
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: textColor,
        fontSize: 10,
        fontFamily: 'SimSun, STKaiti, KaiTi, serif',
        formatter: '{value} 文件',
      },
      axisLine: {
        lineStyle: {
          color: axisLineColor,
          width: 1,
        },
      },
      axisTick: {
        lineStyle: {
          color: axisLineColor,
        },
      },
      splitLine: {
        lineStyle: {
          color: splitLineColor,
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '上传',
        data: uploadDownload.value.data.map((item) => item.upload),
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: uploadColor,
          shadowColor: isDark.value
            ? 'rgba(167, 139, 250, 0.3)'
            : 'rgba(124, 58, 237, 0.3)',
          shadowBlur: 10,
          shadowOffsetY: 8,
        },
        itemStyle: {
          color: uploadColor,
          borderColor: isDark.value ? '#1f2937' : '#f9fafb',
          borderWidth: 1,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: isDark.value
                ? 'rgba(167, 139, 250, 0.3)'
                : 'rgba(124, 58, 237, 0.3)',
            },
            {
              offset: 1,
              color: isDark.value
                ? 'rgba(167, 139, 250, 0.1)'
                : 'rgba(124, 58, 237, 0.1)',
            },
          ]),
        },
      },
      {
        name: '下载',
        data: uploadDownload.value.data.map((item) => item.download),
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: downloadColor,
          shadowColor: isDark.value
            ? 'rgba(103, 232, 249, 0.3)'
            : 'rgba(8, 145, 178, 0.3)',
          shadowBlur: 10,
          shadowOffsetY: 8,
        },
        itemStyle: {
          color: downloadColor,
          borderColor: isDark.value ? '#1f2937' : '#f9fafb',
          borderWidth: 1,
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: isDark.value
                ? 'rgba(103, 232, 249, 0.3)'
                : 'rgba(8, 145, 178, 0.3)',
            },
            {
              offset: 1,
              color: isDark.value
                ? 'rgba(103, 232, 249, 0.1)'
                : 'rgba(8, 145, 178, 0.1)',
            },
          ]),
        },
      },
    ],
  };
});
const pieOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    backgroundColor: isDark.value ? '#1f2937' : '#ffffff',
    borderColor: isDark.value ? '#374151' : '#e5e7eb',
    textStyle: {
      color: isDark.value ? '#f9fafb' : '#111827',
    },
  },
  series: [
    {
      name: '文件类型',
      type: 'pie',
      radius: ['45%', '75%'],
      center: ['50%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 8,
        borderColor: isDark.value ? '#111827' : '#ffffff',
        borderWidth: 2,
      },
      label: {
        show: false,
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '12',
          fontWeight: 'bold',
          color: isDark.value ? '#f9fafb' : '#111827',
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
      labelLine: {
        show: false,
      },
      data: fileTypes.value.map((item) => ({
        value: item.percentage,
        name: item.type,
        itemStyle: { color: item.color },
      })),
    },
  ],
}));
const storageOption = computed(() => ({
  tooltip: {
    formatter: '{b}: {c}%',
  },
  series: [
    {
      name: '存储使用率',
      type: 'pie',
      radius: ['60%', '80%'],
      center: ['50%', '50%'],
      startAngle: 90,
      data: [
        {
          value: stats.value.storageUsed,
          name: '已使用',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#8b5cf6',
                },
                {
                  offset: 1,
                  color: '#ec4899',
                },
              ],
            },
          },
        },
        {
          value: 100 - stats.value.storageUsed,
          name: '可用',
          itemStyle: {
            color: isDark.value ? '#374151' : '#f3f4f6',
          },
          label: {
            show: false,
          },
        },
      ],
      label: {
        show: true,
        position: 'center',
        formatter: '{c}%',
        fontSize: 24,
        fontWeight: 'bold',
        color: isDark.value ? '#f9fafb' : '#111827',
      },
    },
  ],
}));
const router = useRouter();

const handleAction = (action: string) => {
  console.error(`执行操作: ${action}`);
  router.push({
    path: action,
  });
};

onMounted(() => {
  client.statistic
    .getDashboardData()
    .then(({ data }) => {
      // 安全地处理可能为空的数据
      stats.value.uploadedFiles = data?.transferredFiles?.current ?? 0;
      stats.value.uploadedStorage = `${((data?.totalCapacity?.current ?? 0) / 1024 / 1024 / 1024).toFixed(1)} GB`;
      stats.value.activeShares = data?.activeShares?.current ?? 0;
      stats.value.networkSpeed = data?.networkStatus?.connected
        ? '连接正常'
        : '未连接';

      // 安全处理存储数据
      const totalSpace = data?.storageUtilization?.totalSpace ?? 0;
      const usedSpace = data?.storageUtilization?.usedSpace ?? 0;

      stats.value.totalStorage = `${(totalSpace / 1024 / 1024 / 1024).toFixed(0)} GB`;
      stats.value.usedStorage = `${(usedSpace / 1024 / 1024 / 1024).toFixed(0)} GB`;

      // 避免除零错误
      const percentage = totalSpace > 0 ? usedSpace / totalSpace : 0;
      stats.value.storageUsed = Number.parseFloat(
        (percentage * 100).toFixed(2),
      );

      // 安全处理传输活动数据
      uploadDownload.value.data = (data?.transferActivity ?? []).map(
        (item) => ({
          date: item?.time ?? '',
          upload: item?.uploadCount ?? 0,
          download: item?.downloadCount ?? 0,
        }),
      );

      // 安全处理文件类型分布数据
      const fileTypeData = data?.fileTypeDistribution ?? [];
      const totalSize = fileTypeData.reduce(
        (sum, type) => sum + (type?.totalSize ?? 0),
        0,
      );

      fileTypes.value = fileTypeData.map((type) => {
        let name = '';
        let color = '#ccc';

        switch (type?.fileType) {
          case 'DOCUMENT': {
            name = '文档';
            color = '#10b981';
            break;
          }
          case 'IMAGE': {
            name = '图片';
            color = '#06b6d4';
            break;
          }
          case 'OTHER': {
            name = '其他';
            color = '#f59e0b';
            break;
          }
          case 'VIDEO': {
            name = '视频';
            color = '#8b5cf6';
            break;
          }
          default: {
            name = '未知';
            color = '#ccc';
            break;
          }
        }

        // 避免除零错误
        const typeSize = type?.totalSize ?? 0;
        const percentage = totalSize > 0 ? (typeSize / totalSize) * 100 : 0;

        return {
          type: name,
          percentage: Number.parseFloat(percentage.toFixed(2)),
          color,
        };
      });
    })
    .catch((error) => {
      console.error('请求错误:', error);
      // 可以添加错误处理，比如显示默认值或错误提示
    });
});
</script>

<template>
  <div class="container mx-auto max-w-6xl py-8">
    <!-- 页面标题 -->
    <div class="mb-8 text-center">
      <h1 class="mb-3 text-4xl font-bold">文件传输控制中心</h1>
      <p class="text-lg text-gray-600 dark:text-gray-300">
        文件传输与存储控制面板
      </p>
    </div>

    <div>
      <div class="mt-8 flex justify-center space-x-4">
        <button
          @click="handleAction('upload')"
          class="flex items-center rounded-xl bg-blue-500 px-3 py-3 font-semibold text-white shadow transition-all duration-200 hover:shadow-md md:px-6"
        >
          <RocketOutlined class="md:mr-2" />
          <span class="hidden md:inline">开始传输</span>
        </button>
        <button
          @click="handleAction('download')"
          class="flex items-center rounded-xl bg-green-500 px-3 py-3 font-semibold text-white shadow transition-all duration-200 hover:shadow-md md:px-6"
        >
          <DashboardOutlined class="md:mr-2" />
          <span class="hidden md:inline">下载文件</span>
        </button>
        <button
          @click="handleAction('manage')"
          class="flex items-center rounded-xl bg-gray-500 px-3 py-3 font-semibold text-white shadow transition-all duration-200 hover:shadow-md md:px-6"
        >
          <SettingOutlined class="md:mr-2" />
          <span class="hidden md:inline">分享</span>
        </button>
      </div>

      <div class="grid grid-cols-2 gap-4 py-6 sm:grid-cols-2 lg:grid-cols-4">
        <Card
          title="传输统计"
          :icon="CloudUploadOutlined"
          type="primary"
          :content="stats.uploadedFiles"
          class="lg:my-8"
        >
          <template #icon>
            <CloudUploadOutlined />
          </template>
          <template #footer>
            <div class="flex items-center text-sm">
              <span class="mr-1 text-green-500">↗</span>
              <span class="font-medium text-green-500">+23.5%</span>
              <span class="ml-1 text-gray-500 dark:text-gray-400">本周</span>
            </div>
          </template>
        </Card>

        <Card title="文件分析" :icon="PieChartOutlined" type="warning" chart>
          <template #icon>
            <PieChartOutlined />
          </template>
          <template #chart>
            <div class="h-32 w-full">
              <VChart :option="pieOption" autoresize />
            </div>
          </template>
          <template #footer>
            <div class="space-y-2">
              <div
                v-for="type in fileTypes.slice(0, 2)"
                :key="type.type"
                class="flex items-center justify-between text-xs"
              >
                <div class="flex items-center">
                  <div
                    class="mr-2 h-2 w-2 rounded-full"
                    :style="{ backgroundColor: type.color }"
                  ></div>
                  <span class="text-gray-600 dark:text-gray-400">{{
                    type.type
                  }}</span>
                </div>
                <span class="font-medium text-gray-900 dark:text-white">
                  {{ type.percentage }}%
                </span>
              </div>
            </div>
          </template>
        </Card>

        <Card
          title="存储状态"
          :icon="DatabaseOutlined"
          type="primary"
          chart
          class="lg:my-8"
        >
          <template #icon>
            <DatabaseOutlined />
          </template>
          <template #chart>
            <div class="h-20 w-full">
              <VChart :option="storageOption" autoresize />
            </div>
          </template>
          <template #footer>
            <div class="text-center">
              <div class="text-sm text-gray-500 dark:text-gray-400">
                {{ stats.usedStorage }} / {{ stats.totalStorage }}
              </div>
              <div class="mt-1 text-xs text-gray-400 dark:text-gray-500">
                剩余 {{ (500 - 335).toFixed(0) }} GB 可用空间
              </div>
            </div>
          </template>
        </Card>

        <Card
          title="活动监控"
          :icon="EyeOutlined"
          type="primary"
          :content="stats.activeShares"
        >
          <template #icon>
            <EyeOutlined />
          </template>
          <template #footer>
            <div class="space-y-2">
              <div
                v-for="(file, index) in recentFiles.slice(0, 2)"
                :key="index"
                class="flex items-center justify-between"
              >
                <div class="flex min-w-0 flex-1 items-center">
                  <div
                    class="mr-2 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded bg-blue-500 text-xs text-white"
                  >
                    📄
                  </div>
                  <div class="min-w-0 flex-1">
                    <div
                      class="truncate text-xs font-medium text-gray-900 dark:text-white"
                    >
                      {{ file.name.split('.')[0] }}
                    </div>
                    <div class="text-xs text-gray-500 dark:text-gray-400">
                      {{ file.size }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="border-t border-gray-200 pt-2 dark:border-gray-700">
              <button
                class="text-xs font-medium text-blue-600 transition-colors hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
              >
                查看全部活动 →
              </button>
            </div>
          </template>
        </Card>
      </div>

      <!-- 上传下载图表 -->
      <div class="mx-auto mt-8 rounded-xl p-6 shadow">
        <h3 class="mb-4 text-lg font-semibold text-gray-900 dark:text-white">
          上传下载数量
        </h3>
        <div class="h-64 w-full">
          <VChart :option="uploadDownloadOption" autoresize />
        </div>
        <div
          class="mt-4 flex items-center justify-between text-sm text-gray-600 dark:text-gray-300"
        >
          <span>📤 上传: 1247 文件</span>
          <span>📥 下载: 987 文件</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 简化hover动画 */
.group:hover {
  transform: translateY(-2px);
  transition: transform 0.2s ease;
}
</style>
